package com.axc.gallery2.view;
import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Gallery.LayoutParams;
import android.widget.ViewSwitcher.ViewFactory;

import com.axc.gallery2.R;
import com.axc.gallery2.dbhelper.AlbumInfo;
import com.axc.gallery2.dbhelper.ImageInfo;
import com.axc.gallery2.dbhelper.ImagesDBhelper;
import com.axc.gallery2.edit.EditActivity;
import com.axc.gallery2.edit.SinglePicZoom;
import com.axc.gallery2.local.SetScale;
import com.axc.gallery2.menu.RootMenu;
import com.axc.gallery2.net.activity.UploadPhotoActivity;
import com.axc.gallery2.view.gifview.GifView;

/**
 * 滑动显示相片
 */
public class CoverFlowActivity extends Activity implements 
ViewFactory {


	private LinearLayout line;
	private GifView pImageView;
	private PopupWindow popupWindow;
	private View contentView;
	private AlertDialog alertDialog;
	private ImageAdapter imageAdapter;
	private ImageButton imgBtnPopRevert;
	private ImageButton imgBtnPopRew;
	private ImageButton imgBtnPopDel;
	private ImageButton imgBtnPopEdit;
	private ImageButton imgBtnPopZoom;
	private ImageButton imgBtnPopShare;
	private ImageButton imgBtnPopFf;
	private ImageButton imgBtnDesktop;
	private int index = 0;
	private AlbumInfo albumInfo;
	CoverFlow cf;
	private int screenWidth;
	private int screenHeight;

	private boolean isDelSource;

	public View makeView() {
		ImageView imageView = new ImageView(this);
		imageView.setBackgroundColor(0xFF000000);
		imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
		imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return imageView;
	}

	//主题应用
	public static CoverFlowActivity Talbum;
	public int theme = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 主题
        Talbum = this;
        theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
                android.R.style.Theme);
        setTheme(theme);
		super.onCreate(savedInstanceState);
		// 设置不显示标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//获取屏幕大小
		DisplayMetrics dm = new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(dm);     
		int widthPixels= dm.widthPixels;    
		int heightPixels= dm.heightPixels;      
		//float density = dm.density;       
		 screenWidth = (int) (widthPixels ) ;         
		 screenHeight = (int) (heightPixels ) ;
		line = new LinearLayout(this);
		line.setOrientation(LinearLayout.VERTICAL); 
		RootMenu rootMenu = new RootMenu(this);
		rootMenu.initView();
		try {
			rootMenu.iniOnClickListener();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		cf = new CoverFlow(this);
		Bundle bundle = getIntent().getExtras();
		albumInfo =(AlbumInfo)bundle.getSerializable(AlbumInfo.SERALIZABLEKEY);
		imageAdapter =new ImageAdapter(this, albumInfo.getAlbumItems());
		imageAdapter.setSize(screenWidth, screenHeight);
		cf.setAdapter(imageAdapter);
		cf.setAnimationDuration(1500);
		cf.setOnItemLongClickListener(lonClick);
		cf.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {
				// TODO Auto-generated method stub
				showPopWindow(getBitmap(position),view);
				index=position;

			}
		});
		line.addView(rootMenu);
		line.addView(cf,android.view.ViewGroup.LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT);			
		setContentView(line);
		initPopWindow();
		int position = Integer.valueOf(getIntent().getStringExtra(ImageInfo.POSITION));	
		System.out.println("startCoverFlowActivity:"+position);
		cf.setSelection(position);
	}


	public OnItemLongClickListener lonClick = new OnItemLongClickListener() {

		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			
			showPopWindow(getBitmap(position),view);
			index=position;
			return true;
		}
	};


	private String getBitmap(int position) {
//		try {
//			FileInputStream fileInputStream =new FileInputStream(new File(imageAdapter.getList().get(position)));
//			return (InputStream)fileInputStream;
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return imageAdapter.getList().get(position).image_path;		
	}
	
	private void initPopWindow() {  
		// 加载popupWindow的布局文件   
		contentView = LayoutInflater.from(getApplicationContext())  
		.inflate(R.layout.mypopwindow, null);
		pImageView = (GifView) contentView.findViewById(R.id.gifView1);
		
		pImageView.setShowDimension(pImageView.getLayoutParams().width, pImageView.getLayoutParams().height);
		// 声明一个弹出框   
		popupWindow = new PopupWindow(contentView,
				LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);  
		popupWindow.setFocusable(true);
		popupWindow.update(); 
		imgBtnPopRevert = (ImageButton)contentView.findViewById(R.id.imgBtnPopRevert);
		imgBtnPopRevert.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				pImageView.setStop();
				popupWindow.dismiss(); 
			}
		});
		imgBtnPopRew = (ImageButton)contentView.findViewById(R.id.imgBtnPopRew);
		imgBtnPopRew.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(index>0&&index<imageAdapter.getCount()){
					index--;
					pImageView.setGifImage(getBitmap(index));
					cf.setSelection(index);
				}
				else {
					pImageView.setGifImage(getBitmap(0));
					Toast.makeText(getBaseContext(), "第一张", Toast.LENGTH_LONG).show();
				}
			}
		});
		imgBtnPopZoom=(ImageButton)contentView.findViewById(R.id.imgBtnPopZoom);
		imgBtnPopZoom.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent  = new Intent();
				intent.setClass(getBaseContext(), SinglePicZoom.class); 
				Bundle bundle=new Bundle();
				bundle.putString("img", imageAdapter.getList().get(index).image_path);
				intent.putExtra("imgdata", bundle);
				CoverFlowActivity.this.startActivity(intent);
				popupWindow.dismiss(); 
			}
		});
		imgBtnPopEdit = (ImageButton)contentView.findViewById(R.id.imgBtnPopEdit);
		imgBtnPopEdit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent  = new Intent();
				intent.setClass(getBaseContext(), EditActivity.class);
				Log.w("Path", String.valueOf(imageAdapter.getList().get(index)));
				Bundle bundle=new Bundle();
				bundle.putString("pp", imageAdapter.getList().get(index).image_path);
				intent.putExtra("data", bundle);
				CoverFlowActivity.this.startActivity(intent);
				popupWindow.dismiss(); 
			}
		});
		imgBtnPopShare = (ImageButton)contentView.findViewById(R.id.imgBtnPopShare);
		imgBtnPopShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			    Intent intent  = new Intent();
			    intent.setClass(getBaseContext(), UploadPhotoActivity.class);
			    Bundle bundle=new Bundle();
                bundle.putString(ImageInfo.IAMGEPATH, imageAdapter.getList().get(index).image_path);
                intent.putExtra("data", bundle);
                //intent.putExtra(Renren.RENREN_LABEL, renren);
                intent.putExtra("file", new File(imageAdapter.getList().get(index).image_path));
                CoverFlowActivity.this.startActivity(intent);

			}
		});
		imgBtnPopFf = (ImageButton)contentView.findViewById(R.id.imgBtnPopFf);
		imgBtnPopFf.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(index>=0&&index<imageAdapter.getCount()-1){
					index++;
					pImageView.setGifImage(getBitmap(index));
					cf.setSelection(index);
				}
				else {
					pImageView.setGifImage(getBitmap(imageAdapter.getCount()-1));
					Toast.makeText(getBaseContext(), "最后一张", Toast.LENGTH_LONG).show();
				}				
			}
		});
		imgBtnPopDel =(ImageButton)contentView.findViewById(R.id.imgBtnPopDel);
		imgBtnPopDel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				DeleteOper();				
			}
		});
		imgBtnDesktop =(ImageButton)contentView.findViewById(R.id.imgBtnPopDesktop);
		imgBtnDesktop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					SetScale scale  =new SetScale(getBaseContext(),SampleSize.getSampleSize(imageAdapter.getList().get(index).image_path),getWindowManager().getDefaultDisplay());
					scale.start();
					Toast.makeText(getBaseContext(), "设置成功！", Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
				}				
			}
		});
		
	}



	private void showPopWindow(String path,View view) {
		pImageView.setGifImage(path);
		popupWindow.showAtLocation(view,Gravity.CENTER,0,0);
	}
	/**
	 * 删除操作
	 * 
	 */
	private void DeleteOper() {
	    alertDialog = new	AlertDialog.Builder(this)
		.setPositiveButton(R.string.sure,new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
				final GalleryProgressDialog galleryProgressDialog =	new GalleryProgressDialog( CoverFlowActivity.this) {

					@Override
					public void setRun() {
						//逐一标记条目
						String path;
							path=imageAdapter.getList().get(index).image_path;
							System.out.println("删除源文件:"+path+":"+isDelSource);
							ImagesDBhelper imagesDBhelper =new ImagesDBhelper(getBaseContext());
							//删除源文件
							if(isDelSource){
								File file = new File(path);
								if(file.exists()){
									file.delete();
								}		
								//删除相关数据
								imagesDBhelper.deleteImage(path);
							}
							else {
								imagesDBhelper.deleteImage(albumInfo.getAlbumId(), path);
							}
							imageAdapter.removeAt(index);
							

					}
				};
				galleryProgressDialog.setHandler(new Handler(){

					@Override
					public void handleMessage(Message msg) {
						imageAdapter.notifyDataSetChanged();
						galleryProgressDialog.dismiss();
						Toast.makeText(CoverFlowActivity.this, R.string.album_delsuccess, Toast.LENGTH_LONG).show();
					}

				});
				galleryProgressDialog.showGalleryProgressDialog();

			}
		})
		.setNegativeButton(R.string.cancel, null).setMultiChoiceItems(new String[]{getString(R.string.gridview_dialog_delesourcefiles)},new boolean[1],new OnMultiChoiceClickListener() {



			@Override
			public void onClick(DialogInterface arg0, int arg1, boolean isChecked) {
				isDelSource = isChecked;
			}
		})
		.setTitle(R.string.dialogtitle).create();
		alertDialog.show();
	}
	

}

